package cn.jly.akka.actors_communicate

import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import com.typesafe.config.{Config, ConfigFactory}

object ServerActorApp extends App {
  // 服务器ip
  val host: String = "127.0.0.1"
  // 服务器端口
  val port: Int = 9999
  // ServerActorSystem的名字
  val serverActorSystemName: String = "serverActorSystem"
  // serverActorRef的名字
  val serverActorRefName: String = "serverActorRef"

  // 服务端actorSystem的config
  private val config: Config = ConfigFactory.parseString(
    s"""
       |akka.actor.provider="akka.remote.RemoteActorRefProvider"
       |akka.remote.netty.tcp.hostname=$host
       |akka.remote.netty.tcp.port=$port
      """.stripMargin)

  // 获得server actorSystem
  private val serverActorSystem: ActorSystem = ActorSystem(serverActorSystemName, config)
  // 获得server actorRef
  private val serverActorRef: ActorRef = serverActorSystem.actorOf(Props[ServerActor], serverActorRefName)

  // 开始运行serverActorRef
  serverActorRef ! "start"
}

// 服务器actor
class ServerActor extends Actor {
  override def receive: Receive = {
    // 收到start指令
    case "start" => println("收到start指令，服务端serverActor开始工作..")
    // 收到客户端消息
    case ClientMessage(msg) => {
      msg match {
        // 匹配到问题之后回复消息
        case "公司名称缩写" => sender() ! ServerMessage("hxfz")
        case "公司地址" => sender() ! ServerMessage("南京")
        case _ => sender() ! ServerMessage("未知提问")
      }
    }
  }
}